/**
 * 缓存工具类
 * 使用 quick-lru 实现高效的内存缓存
 */
import QuickLRU from 'quick-lru'

// 创建不同用途的缓存实例
const assetCache = new QuickLRU<string, any>({ maxSize: 500 }) // 素材缓存
const renderCache = new QuickLRU<string, any>({ maxSize: 100 }) // 渲染结果缓存
const computeCache = new QuickLRU<string, any>({ maxSize: 200 }) // 计算结果缓存

/**
 * 缓存服务
 */
export const CacheService = {
  /**
   * 素材缓存
   */
  getAsset(key: string) {
    return assetCache.get(key)
  },

  setAsset(key: string, value: any) {
    assetCache.set(key, value)
  },

  /**
   * 渲染缓存
   */
  getRender(key: string) {
    return renderCache.get(key)
  },

  setRender(key: string, value: any) {
    renderCache.set(key, value)
  },

  /**
   * 计算缓存
   */
  getCompute(key: string) {
    return computeCache.get(key)
  },

  setCompute(key: string, value: any) {
    computeCache.set(key, value)
    return value
  },

  /**
   * 使用缓存执行函数
   * @param fn 要执行的函数
   * @param keyGenerator 缓存键生成函数
   * @returns 包装后的函数
   */
  memoize<T extends (...args: any[]) => any>(
    fn: T,
    keyGenerator: (...args: Parameters<T>) => string
  ): T {
    return ((...args: Parameters<T>): ReturnType<T> => {
      const key = keyGenerator(...args)
      const cached = this.getCompute(key)

      if (cached !== undefined) {
        return cached as ReturnType<T>
      }

      const result = fn(...args)
      return this.setCompute(key, result) as ReturnType<T>
    }) as T
  },

  /**
   * 清除特定缓存
   * @param type 缓存类型
   */
  clear(type: 'asset' | 'render' | 'compute' | 'all') {
    switch (type) {
      case 'asset':
        assetCache.clear()
        break
      case 'render':
        renderCache.clear()
        break
      case 'compute':
        computeCache.clear()
        break
      case 'all':
        assetCache.clear()
        renderCache.clear()
        computeCache.clear()
        break
    }
  },

  /**
   * 序列化对象，用于生成缓存键
   * @param obj 要序列化的对象
   * @returns 序列化后的字符串
   */
  serialize(obj: any): string {
    return JSON.stringify(obj, (key, value) => {
      // 处理特殊类型，如 Date、RegExp 等
      if (value instanceof Date) {
        return { __type: 'Date', value: value.toISOString() }
      }
      if (value instanceof RegExp) {
        return { __type: 'RegExp', source: value.source, flags: value.flags }
      }
      return value
    })
  },
  
  /**
   * 获取缓存状态
   * @returns 缓存状态信息
   */
  getStatus() {
    return {
      asset: {
        size: assetCache.size,
        maxSize: assetCache.maxSize
      },
      render: {
        size: renderCache.size,
        maxSize: renderCache.maxSize
      },
      compute: {
        size: computeCache.size,
        maxSize: computeCache.maxSize
      }
    }
  }
} 